package com.match.competition_role.service.impl;

import com.alibaba.fastjson.JSON;
import com.match.commonutils.Result;
import com.match.competition_role.client.RoleClient;
import com.match.competition_role.service.CompetitionPermissionService;
import com.match.competition_security.filter.SecurityUser;
import com.match.entity.baseEntity.Student;
import com.match.entity.loginEntity.LoginUser;
import com.match.entity.baseEntity.Teacher;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 芊薰
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RoleClient roleClient;
    @Autowired
    private CompetitionPermissionService competitionPermissionService;


    /**
     * 根据用户职工号的到用户以及权限
     *
     * @param number
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String number) throws UsernameNotFoundException {
        //根据职工号查询用户
        Object teaInfo = roleClient.getTeaByNum(number).getData().get("teaInfo");
        String s = JSON.toJSONString(teaInfo);
        Teacher teacher = JSON.parseObject(s, Teacher.class);
        if (StringUtils.isEmpty(teacher)) {
            //根据学号查询学生
            Object stuInfo = roleClient.findStuByNum(number).getData().get("stuInfo");
            String string = JSON.toJSONString(stuInfo);
            Student student = JSON.parseObject(string, Student.class);
            if (StringUtils.isEmpty(student)){
                throw new UsernameNotFoundException("用户名或密码不正确");
            }
            //返回UserDetails实现类
            LoginUser user = new LoginUser();
            BeanUtils.copyProperties(student, user);

            List<String> authorities = competitionPermissionService.selectPermissionValueByTeacherNumber(user.getNumber());
            SecurityUser securityUser = new SecurityUser(user);
            securityUser.setPermissionValueList(authorities);
            return securityUser;
        }
        //返回UserDetails实现类
        LoginUser user = new LoginUser();
        BeanUtils.copyProperties(teacher, user);

        List<String> authorities = competitionPermissionService.selectPermissionValueByTeacherNumber(user.getNumber());
        SecurityUser securityUser = new SecurityUser(user);
        securityUser.setPermissionValueList(authorities);
        return securityUser;
    }
}
